package com.liqi.frame.comm.base;

import freemarker.cache.MultiTemplateLoader;
import freemarker.cache.TemplateLoader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.File;
import java.util.Map;

/**
 * Created by liqi on 2019/9/18 0018.
 */
public abstract class BaseNavController {
    String ctrlName="";
    @Autowired
    org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer _fmc;
    //static freemarker.cache.FileTemplateLoader _ftl = null;
    static String _templateLoaderPath=null;

    public BaseNavController(String controllerName){
        ctrlName= controllerName.toLowerCase();
    }

    boolean initTemplateLoaderPath() {
        if(_templateLoaderPath!=null)
            return true;
        gsPrintln("_fmc = {0}", _fmc==null?"null":_fmc.toString());
        //布局模板是否存在
        if(_fmc!=null){
            MultiTemplateLoader utll = (MultiTemplateLoader)_fmc
                    .getConfiguration()
                    .getTemplateLoader();
            int n=utll.getTemplateLoaderCount();
            gsPrintln("TemplateLoaderCount="+n);
            TemplateLoader tl = null;
            File file = null;
            for(int i=0;i<n;i++) {
                tl= utll.getTemplateLoader(i);
                gsPrintln(tl.toString());
                //获取模板加载目录地址
                if(tl instanceof freemarker.cache.FileTemplateLoader){
                    _templateLoaderPath = ((freemarker.cache.FileTemplateLoader)tl)
                            .getBaseDirectory()
                            .getAbsolutePath();
                }
            }
        }
        gsPrintln("freemark 模板地址：{0}", _templateLoaderPath);
        return _templateLoaderPath!=null;
    }

    boolean IsExistsTemplate(String filePath){
        initTemplateLoaderPath();
        File file = new File(gsFormat("{0}/{1}", _templateLoaderPath,filePath));
        boolean exist = file.exists();
        gsPrintln("viewer[{1}]:{0}",file,exist);
        return exist;
    }
    /**
     * 公共视图解析器：controllerName/viewer/{file}/{prefix}
     * @param prefix
     * @param pars
     * @return
     */
    @RequestMapping("viewer/{prefix}")
    public String viewer(@PathVariable String prefix,Map<String, Object> pars){
        return freeMarkerViewResult(prefix, pars);//布局模板
    }
    /**
     * freemarker 布局视图解析
     * @param prefix
     * @param pars
     * @return
     */
    public String freeMarkerViewResult(String prefix, Map<String, Object> pars){
        //布局模板
        String layout = gsFormat("{0}/layout/{1}Layout.ftl", ctrlName,prefix);
        //js内容
        String js = gsFormat("{0}/js/{1}Js.js", ctrlName,prefix);
        if(!IsExistsTemplate(js)){
            js="";//不存在时，地址赋值为空
        }
        //页模板
        String body = gsFormat("{0}/pub/{1}Viewer.ftl", ctrlName,prefix);

        //页面参数
        pars.put("body_file_path", body);
        pars.put("js_file_path", js);

        //优先使用布局页
        if(IsExistsTemplate(layout)){
            return layout.replaceAll("\\.ftl$", ""); //模板不需要后缀
        }
        return body.replaceAll("\\.ftl$", "");//模板不需要后缀
    }



    public static void gsPrintln(String msg, Object... args){
        System.out.println(gsFormat(msg,args));
    }
    /**
     * 字符串内容格式化输出，内部使用{0}\{1}\{2}...为参数占位符
     * @param msg 格式化模板
     * @param args 不固定参数
     * @return
     */
    public static String gsFormat(String msg, Object... args)
    {
        return java.text.MessageFormat.format(msg, args);
    }
}
